package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.service.I18nService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.i18n.pojo.dto.SetLangPackDTO;
import com.xbongbong.pro.i18n.pojo.vo.SetLangPackVO;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 国际化相关接口
 *
 * @author kaka
 * @version v1.0
 * @date 2020/4/21 10:21
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/pc/i18n")
public class WebI18nController {

    @Resource
    private I18nService i18nService;

    /**
     * 设置语言包接口
     * @param setLangPackDTO 设置语言包入参
     * @param br DTO参数校验返回
     * @return 接口返回json格式
     */
    @RequestMapping(value = "/setLangPack", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String setLangPack(@RequestBody @Valid SetLangPackDTO setLangPackDTO, BindingResult br) {
        XbbResponse<SetLangPackVO> response;
        if(br.hasErrors()){
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                SetLangPackVO setLangPackVO = i18nService.setLangPack(setLangPackDTO);
                response = new XbbResponse<>(setLangPackVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

}
